<?php
namespace com\rs\dns\controller\install;

use com\rs\dns\controller\BaseController;
use com\rs\dns\service\InstallService;
use restphp\http\RestHttpRequest;
use restphp\http\RestHttpResponse;

/**
 * Class InstallController
 * @package com\rs\dns\controller
 * @RequestMapping(value="/install")
 */
final class InstallController extends BaseController {
    /**
     * 安装引导页.
     * @RequestMapping(value="", method="GET")
     * @throws \restphp\exception\RestException
     */
    public function install() {
        $this->_tpl->display("bk-install.tpl");
    }

    /**
     * 环镜检查.
     * @RequestMapping(value="/env", method="GET")
     */
    public function envCheck() {
        $strCheckResult = "";
        $arrCheckRow = array(
            'install_dir' => array(
                'flag' => 0,
                'name' => '安装操作记录文件',
                'file' => InstallService::getInstallFilePath()
            ),
            'config_dir' =>  array(
                'flag' => 0,
                'name' => '安装配置记录文件',
                'file' => InstallService::getConfigFile()
            ),
            'php_odbc_connect' => array(
                'flag' => 0,
                'name' => 'PHP PDO_ODBC环境检查',
                'file' => 'pdo_odbc'
            )
        );
        do {
            if (InstallService::bIsInstall()) {
                $strCheckResult = "系统已进行过安装，请勿重复操作";
                $nCanInstall = 0;
                break;
            }

            $nCanInstall = 1;

            $arrCheckRow['install_dir']['flag'] = InstallService::bInstallLockCanWrite() ? 1 : 0;
            $arrCheckRow['config_dir']['flag'] = InstallService::bConfigCanWrite() ? 1 : 0;

            $nCanInstall = ($arrCheckRow['install_dir']['flag'] == 1 && $arrCheckRow['config_dir']['flag'] == 1) ? 2 : $nCanInstall;
        } while(false);

        //检查php扩展环镜
        if (extension_loaded('php_odbc') || extension_loaded('PDO_ODBC')) {
            $arrCheckRow['php_odbc_connect']['flag'] = 1;
        } else {
            $arrCheckRow['php_odbc_connect']['flag'] = 0;
            $nCanInstall = 1;
        }

        RestHttpResponse::json(array(
            "result" => $nCanInstall,
            "msg" => $strCheckResult,
            "row" => $arrCheckRow
        ));
    }

    /**
     * 安装.
     * @RequestMapping(value="/make", method="POST")
     */
    public function makeInstall() {
        $installForm = RestHttpRequest::getRequestBody(new InstallForm(), true);
        InstallService::install($installForm);
        RestHttpResponse::json(array(
            'result' => 1,
            'msg' => '安装配置成功'
        ));
    }
}